package com.luckcoder.relax.games.controller;

import com.luckcoder.relax.games.domain.bo.RelaxAudioConfigBo;
import com.luckcoder.relax.games.domain.bo.RelaxBlessingConfigBo;
import com.luckcoder.relax.games.domain.bo.RelaxUserGameSettingsBo;
import com.luckcoder.relax.games.domain.vo.MiniappGameVo;
import com.luckcoder.relax.games.domain.vo.RelaxAudioConfigVo;
import com.luckcoder.relax.games.domain.vo.RelaxBlessingConfigVo;
import com.luckcoder.relax.games.domain.vo.RelaxUserGameSettingsVo;
import com.luckcoder.relax.games.domain.dto.GameFinishData;
import com.luckcoder.relax.games.domain.dto.UserGameStats;
import com.luckcoder.relax.games.domain.dto.GlobalGameStats;
import com.luckcoder.relax.games.domain.dto.EmojiRankingItem;
import com.luckcoder.relax.games.service.IMiniappGameService;
import com.luckcoder.relax.games.service.IRelaxAudioConfigService;
import com.luckcoder.relax.games.service.IRelaxBlessingConfigService;
import com.luckcoder.relax.games.service.IRelaxUserGameSettingsService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 小程序游戏控制器
 *
 * @author zhanghao
 * @date 2025-09-10
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/miniapp/game")
public class MiniappGameController {
    
    private final IMiniappGameService miniappGameService;
    private final IRelaxBlessingConfigService relaxBlessingConfigService;
    private final IRelaxAudioConfigService relaxAudioConfigService;
    private final IRelaxUserGameSettingsService relaxUserGameSettingsService;
    
    /**
     * 获取可用的游戏列表
     */
    @GetMapping("/list")
    public R<List<MiniappGameVo>> getGameList() {
        List<MiniappGameVo> gameList = miniappGameService.getAvailableGames();
        return R.ok(gameList);
    }
    
    /**
     * 记录游戏开始
     */
    @PostMapping("/start/{gameCode}")
    public R<Long> startGame(@PathVariable String gameCode) {
        Long recordId = miniappGameService.startGame(gameCode);
        return R.ok(recordId);
    }
    
    /**
     * 结束游戏并保存详细数据
     *
     * @param recordId 游戏记录ID
     * @param gameFinishData 游戏结束数据
     * @return 操作结果
     */
    @PostMapping("/finish/{recordId}")
    public R<Void> finishGame(@PathVariable Long recordId, @RequestBody GameFinishData gameFinishData) {
        miniappGameService.finishGame(recordId, gameFinishData);
        return R.ok();
    }
    
    /**
     * 获取用户游戏统计数据
     *
     * @param gameCode 游戏编码
     * @return 统计数据
     */
    @GetMapping("/stats/user/{gameCode}")
    public R<UserGameStats> getUserGameStats(@PathVariable String gameCode) {
        UserGameStats stats = miniappGameService.getUserGameStats(gameCode);
        return R.ok(stats);
    }
    
    /**
     * 获取全局游戏统计数据
     *
     * @param gameCode 游戏编码
     * @return 全局统计数据
     */
    @GetMapping("/stats/global/{gameCode}")
    public R<GlobalGameStats> getGlobalGameStats(@PathVariable String gameCode) {
        GlobalGameStats stats = miniappGameService.getGlobalGameStats(gameCode);
        return R.ok(stats);
    }
    
    /**
     * 获取Emoji消灭排行榜
     *
     * @param gameCode 游戏编码
     * @param limit 返回数量限制，默认20
     * @return Emoji排行榜
     */
    @GetMapping("/stats/emoji/ranking/{gameCode}")
    public R<List<EmojiRankingItem>> getEmojiRanking(@PathVariable String gameCode, 
                                                     @RequestParam(defaultValue = "20") Integer limit) {
        List<EmojiRankingItem> ranking = miniappGameService.getEmojiRanking(gameCode, limit);
        return R.ok(ranking);
    }
    
    /**
     * 获取游戏祝福语配置
     *
     * @param gameCode 游戏编码
     * @return 祝福语列表
     */
    @GetMapping("/blessings/{gameCode}")
    public R<List<RelaxBlessingConfigVo>> getBlessings(@PathVariable String gameCode) {
        RelaxBlessingConfigBo bo = new RelaxBlessingConfigBo();
        bo.setGameCode(gameCode);
        bo.setStatus("0"); // 正常状态
        bo.setIsEnabled("1"); // 启用状态
        List<RelaxBlessingConfigVo> blessings = relaxBlessingConfigService.queryList(bo);
        return R.ok(blessings);
    }
    
    /**
     * 获取游戏音效配置
     *
     * @param gameCode 游戏编码
     * @return 音效配置列表
     */
    @GetMapping("/audios/{gameCode}")
    public R<List<RelaxAudioConfigVo>> getAudios(@PathVariable String gameCode) {
        RelaxAudioConfigBo bo = new RelaxAudioConfigBo();
        bo.setGameCode(gameCode);
        bo.setStatus("0"); // 正常状态
        bo.setIsEnabled("1"); // 启用状态
        List<RelaxAudioConfigVo> audios = relaxAudioConfigService.queryList(bo);
        return R.ok(audios);
    }
    
    /**
     * 根据类型获取游戏祝福语配置
     *
     * @param gameCode     游戏编码
     * @param blessingType 祝福语类型 (chinese/english/mixed/general)
     * @return 祝福语列表
     */
    @GetMapping("/blessings/{gameCode}/{blessingType}")
    public R<List<RelaxBlessingConfigVo>> getBlessingsByType(@PathVariable String gameCode,
                                                             @PathVariable String blessingType) {
        RelaxBlessingConfigBo bo = new RelaxBlessingConfigBo();
        bo.setGameCode(gameCode);
        bo.setBlessingType(blessingType);
        bo.setStatus("0"); // 正常状态
        bo.setIsEnabled("1"); // 启用状态
        List<RelaxBlessingConfigVo> blessings = relaxBlessingConfigService.queryList(bo);
        return R.ok(blessings);
    }
    
    /**
     * 根据类型获取游戏音效配置
     *
     * @param gameCode  游戏编码
     * @param audioType 音效类型 (pop/eliminate/background/click/success)
     * @return 音效配置列表
     */
    @GetMapping("/audios/{gameCode}/{audioType}")
    public R<List<RelaxAudioConfigVo>> getAudiosByType(@PathVariable String gameCode,
                                                       @PathVariable String audioType) {
        RelaxAudioConfigBo bo = new RelaxAudioConfigBo();
        bo.setGameCode(gameCode);
        bo.setAudioType(audioType);
        bo.setStatus("0"); // 正常状态
        bo.setIsEnabled("1"); // 启用状态
        List<RelaxAudioConfigVo> audios = relaxAudioConfigService.queryList(bo);
        return R.ok(audios);
    }
    
    /**
     * 获取用户游戏设置
     *
     * @param gameCode 游戏编码
     * @return 用户游戏设置
     */
    @GetMapping("/settings/{gameCode}")
    public R<RelaxUserGameSettingsVo> getUserGameSettings(@PathVariable String gameCode) {
        // 这里需要获取当前登录用户ID，暂时使用硬编码
        Long userId = 1L; // TODO: 从安全上下文获取当前用户ID
        RelaxUserGameSettingsVo settings = relaxUserGameSettingsService.queryByUserAndGame(userId, gameCode);
        
        // 如果没有设置则返回默认设置
        if (settings == null) {
            settings = getDefaultGameSettings(gameCode);
        }
        
        return R.ok(settings);
    }
    
    /**
     * 保存用户游戏设置
     *
     * @param gameCode 游戏编码
     * @param settingsBo 游戏设置数据
     * @return 操作结果
     */
    @PostMapping("/settings/{gameCode}")
    public R<Void> saveUserGameSettings(@PathVariable String gameCode, 
                                        @RequestBody RelaxUserGameSettingsBo settingsBo) {
        // 这里需要获取当前登录用户ID，暂时使用硬编码
        Long userId = 1L; // TODO: 从安全上下文获取当前用户ID
        
        settingsBo.setUserId(userId);
        settingsBo.setGameCode(gameCode);
        
        boolean success = relaxUserGameSettingsService.saveUserGameSettings(settingsBo);
        if (success) {
            return R.ok();
        } else {
            return R.fail("保存游戏设置失败");
        }
    }
    
    /**
     * 获取默认游戏设置
     *
     * @param gameCode 游戏编码
     * @return 默认设置
     */
    private RelaxUserGameSettingsVo getDefaultGameSettings(String gameCode) {
        RelaxUserGameSettingsVo defaultSettings = new RelaxUserGameSettingsVo();
        defaultSettings.setGameCode(gameCode);
        
        // 根据游戏类型设置默认值
        if ("emoji_eliminate".equals(gameCode)) {
            defaultSettings.setGameTime(60);
            defaultSettings.setEmojiSpeed(300);
            defaultSettings.setMaxEmojis(8);
            defaultSettings.setEmojiSizeMin(80);
            defaultSettings.setEmojiSizeMax(120);
            defaultSettings.setAutoPopTime(5);
        }
        
        return defaultSettings;
    }
}